//
//  zhuceViewController.m
//  ManageMoney
//
//  Created by Kiss on 15/10/23.
//  Copyright © 2015年 db. All rights reserved.
//

#import "zhuceViewController.h"
#import "HomeViewController.h"

#define kAlphaNum   @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

@interface zhuceViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIGestureRecognizerDelegate,UITextFieldDelegate,UIScrollViewDelegate>
{
    UIAlertView *photoAlert;
    NSDictionary *areaDic;
    NSArray *province;
    NSArray *city;
    NSString *str;
    
    NSString *selBtn;
    
    NSInteger biaoshi1;
    NSString *picture1;
    NSString *picture2;
}

@property (strong, nonatomic) IBOutlet UITextField *userName;
@property (strong, nonatomic) IBOutlet UITextField *shenfenzhang;

@property (strong, nonatomic) IBOutlet UITextField *tuiJianMan;
@property (nonatomic, strong) UIPickerView *pickerView;
@property (weak, nonatomic) IBOutlet UIImageView *uiImage1;
@property (weak, nonatomic) IBOutlet UIImageView *uiImage2;
@property (weak, nonatomic) IBOutlet UIScrollView *mainScrollView;

@end

@implementation zhuceViewController
@synthesize lastChosenMediaType;

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title =@"个人资料";
    self.uiImage1.userInteractionEnabled = YES;
    self.uiImage2.userInteractionEnabled = YES;
    [self.uiImage1 addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(uiImage1:)]];
    [self.uiImage2 addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(uiImage2:)]];
    
    self.mainScrollView.delegate = self;
}


-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    
    
    [self.mainScrollView setContentSize:CGSizeMake(ScreenWith, 600)];
    
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}

-(void)uiImage1:(UITapGestureRecognizer*)recognizer
{
    biaoshi1 = 1;
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    
    picker.delegate = self;
    
    //设置选择后的图片可被编辑
    
    picker.allowsEditing = YES;
    
    //    [self presentModalViewController:picker animated:YES];
    [self presentViewController:picker animated:YES completion:nil];
    
    
}

-(void)uiImage2:(UITapGestureRecognizer*)recognizer
{
    biaoshi1=2;
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    
    picker.delegate = self;
    
    //设置选择后的图片可被编辑
    
    picker.allowsEditing = YES;
    
    //    [self presentModalViewController:picker animated:YES];
    [self presentViewController:picker animated:YES completion:nil];
   
    
}


//当选择一张图片后进入这里

-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    
    
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"])
    {
        
        
        if (biaoshi1 ==1) {
            //先把图片转成NSData
            UIImage* image1 = [info objectForKey:@"UIImagePickerControllerEditedImage"];
            NSData *imgdata1 = UIImageJPEGRepresentation(image1, 0.75);
            _uiImage1.image = image1;
            
            NSString *imgdata1Url = [@"" stringByAppendingFormat:@"%@%@",hrtxUrl,@"cust/uploadImg.do"];
            ZWFormData *zwData= [[ZWFormData alloc]init];
            zwData.data = imgdata1;
            zwData.name = @"file";
            zwData.filename = @"1.png";
            zwData.mimeType = @"image/png";
            
            NSArray *imageArray = [[NSArray alloc]initWithObjects:zwData, nil];
            
            [SVProgressHUD show];
            [self.view endEditing:YES];
            
            [HWHttpTool postWithURL:imgdata1Url params:nil formDataArray:imageArray success:^(id json) {
                [SVProgressHUD dismiss];
                NSDictionary *dic = json;
                NSLog(@"字典-%@",dic);
                if ([dic[@"responseCode"] intValue] == 200) {
                    
                    NSLog(@"图片1上传成功");
                    picture1 = dic[@"responseObj"];
                }else
                {
                    [SVProgressHUD showErrorWithStatus:dic[@"responseMessage"]];
                }
                
            } failure:^(NSError *error) {
                NSLog(@"图片1错误：%@",error);
                [SVProgressHUD dismiss];
                
            }];

        }else if(biaoshi1 ==2){
            //先把图片转成NSData
            UIImage* image2 = [info objectForKey:@"UIImagePickerControllerEditedImage"];
            NSData *imgdata2 = UIImageJPEGRepresentation(image2, 0.75);
            _uiImage2.image = image2;
            
            NSString *imgdata1Url = [@"" stringByAppendingFormat:@"%@%@",hrtxUrl,@"cust/uploadImg.do"];
            ZWFormData *zwData= [[ZWFormData alloc]init];
            zwData.data = imgdata2;
            zwData.name = @"file";
            zwData.filename = @"2.png";
            zwData.mimeType = @"image/png";
            
            NSArray *imageArray = [[NSArray alloc]initWithObjects:zwData, nil];
            
            [SVProgressHUD show];
            [self.view endEditing:YES];
            
            [HWHttpTool postWithURL:imgdata1Url params:nil formDataArray:imageArray success:^(id json) {
                [SVProgressHUD dismiss];
                NSDictionary *dic = json;
                if ([dic[@"responseCode"] intValue] == 200) {
                    
                    NSLog(@"图片2上传成功");
                    picture2 = dic[@"responseObj"];
                }else
                {
                    [SVProgressHUD showErrorWithStatus:dic[@"responseMessage"]];
                }
                
            } failure:^(NSError *error) {
                NSLog(@"图片2错误：%@",error);
                [SVProgressHUD dismiss];
                
            }];
        }
        
       
        [picker dismissViewControllerAnimated:YES completion:nil];
        
    }
    
}






#pragma mark - textField delegate


- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}
- (BOOL)textField:(UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string {
    //限制身份证号  只能输字母和数字
    if (textField == self.shenfenzhang) {
        NSCharacterSet *cs;
        cs = [[NSCharacterSet characterSetWithCharactersInString:kAlphaNum] invertedSet];
        NSString *filtered =
        [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
        BOOL basic = [string isEqualToString:filtered];
        return basic;
    }
    
    return YES;
}

- (IBAction)baocun:(id)sender {
    [self TextfieldresignfirstResponder];
    if ([_userName.text.trim isEqualToString:@""]) {
        [SVProgressHUD showErrorWithStatus:@"请输入名字"];
        return;
    }
    if ([_shenfenzhang.text.trim isEqualToString:@""]) {
        [SVProgressHUD showErrorWithStatus:@"身份证号码不能为空"];
        return;
    }
    
    NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    [identityCardPredicate evaluateWithObject:_shenfenzhang.text];
    
    if ([identityCardPredicate evaluateWithObject:_shenfenzhang.text] == NO) {
        [SVProgressHUD showErrorWithStatus:@"请输入正确格式的身份证号"];
        return;
    }
  
    if ([_tuiJianMan.text.trim isEqualToString:@""]) {
        [SVProgressHUD showErrorWithStatus:@"推荐码不能为空"];
        return;
    }
    if (picture1.length <2) {
        [SVProgressHUD showErrorWithStatus:@"身份证正面照"];
        return;
    }
    
    if (picture2.length <2) {
        [SVProgressHUD showErrorWithStatus:@"身份证半身照"];
        return;
    }
    
    
    
    
    
    NSString *RegisterMessageUrl = [@"" stringByAppendingFormat:@"%@%@",hrtxUrl,@"cust/auth.do"];
    [SVProgressHUD show];
    NSDictionary *pramas  = [[NSDictionary alloc]init];
    pramas = @{@"customerNum":self.zhuceStr,@"idCard":_shenfenzhang.text,@"registerCode":_tuiJianMan.text,@"name":_userName.text,@"SFZ_ZMZ_Str":picture1,@"SFZ_BSZ_Str":picture2};

    
    [HWHttpTool postWithURL:RegisterMessageUrl params:pramas formDataArray:nil success:^(id json) {
        NSLog(@"%@",json);
        [SVProgressHUD dismiss];
        NSDictionary *dic = json;
        if ([dic[@"responseCode"] intValue] == 200) {
            NSDictionary *userDic = dic[@"responseObj"];
            [UserDefaults setObject:userDic forKey:kUserInfo];
            [UserDefaults synchronize];
            
            HomeViewController *home = [[HomeViewController alloc]initWithNibName:@"HomeViewController" bundle:nil];
            [self.navigationController pushViewController:home animated:YES];
        }else
        {
            [SVProgressHUD showErrorWithStatus:dic[@"responseMessage"]];
        }
    } failure:^(NSError *error) {
       NSLog(@"错误：%@",error);
        [SVProgressHUD dismiss];
        
    }];

}




-(void)TextfieldresignfirstResponder
{
    [self.userName resignFirstResponder];
    [self.shenfenzhang resignFirstResponder];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

@end
